package cn.bonoon.kernel.web;

import java.util.ArrayList;
import java.util.List;

/**
 * 对html文本的转义处理
 * @author jackson
 *
 */
public class HtmlEscapeCharacter {
	
	private final List<EscapeMapped> valueMappeds = new ArrayList<>();
	private final List<EscapeMapped> textMappeds = new ArrayList<>();
	
	public HtmlEscapeCharacter(){
		add(textMappeds, "<", "&lt;");
		add(textMappeds, ">", "&gt;");
//		add("&", "&amp;");
		add(valueMappeds, "\"", "&quot;");
		add(valueMappeds, "'", "&apos;");
	}
	
	public void add(List<EscapeMapped> mappeds, String source, String target){
		mappeds.add(new EscapeMapped(source, target));
	}
	
	private class EscapeMapped{
		
		private final String source;
		private final String target;
		
		EscapeMapped(String source, String target){
			this.source = source;
			this.target = target;
		}
	}
	
	public Object value(Object val){
		return internalResolve(valueMappeds, val);
	}
	
	public Object text(Object val){
		return internalResolve(textMappeds, val);
	}
	
	private Object internalResolve(List<EscapeMapped> mappeds, Object val){
		if(val instanceof String){
			String str = (String)val;
			for(EscapeMapped sm : mappeds){
				str = str.replaceAll(sm.source, sm.target);
			}
			return str;
		}
		if(null == val) return "";
		return val;
	}
}
